package cn.com.greatwall.flowable.identity;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.flowable.idm.api.Group;
import org.flowable.idm.engine.IdmEngineConfiguration;
import org.flowable.idm.engine.impl.GroupQueryImpl;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntity;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityImpl;
import org.flowable.idm.engine.impl.persistence.entity.GroupEntityManagerImpl;
import org.flowable.idm.engine.impl.persistence.entity.data.GroupDataManager;
import org.springframework.beans.factory.annotation.Autowired;

import cn.com.greatwall.system.modules.system.service.JobService;
import cn.com.greatwall.system.modules.system.service.dto.JobDto;
import cn.com.greatwall.system.modules.system.service.dto.criteria.JobQueryCriteria;

/**
 * @Author herw
 * @Time 2020-09-22 13:16:36
 * @Version 1.0
 * @Description: TODO(用一句话描述该文件做什么)
 */
public class CustomGroupEntityManager extends GroupEntityManagerImpl {
    @Autowired
    private JobService jobService;

    public CustomGroupEntityManager(IdmEngineConfiguration idmEngineConfiguration, GroupDataManager groupDataManager) {
        super(idmEngineConfiguration, groupDataManager);
    }

    @Override
    public GroupEntity findById(String entityId) {
        JobDto job = jobService.findById(Long.parseLong(entityId));
        if (job == null) {
            return null;
        }
        GroupEntity groupEntity = new GroupEntityImpl();
        groupEntity.setId(job.getId().toString());
        groupEntity.setName(job.getName());
        return groupEntity;
    }

    @Override
    public List<Group> findGroupByQueryCriteria(GroupQueryImpl query) {
        JobQueryCriteria criteria = new JobQueryCriteria();
        if (ObjectUtils.isNotEmpty(query.getId())) {
            criteria.setId(Long.parseLong(query.getId()));
        }
        criteria.setName(query.getName());
        List<JobDto> jobs = jobService.queryAll(criteria);
        if (jobs == null || jobs.size() == 0) {
            return new ArrayList<>();
        }
        List<Group> groups = new ArrayList<>();
        for (JobDto job : jobs) {
            Group group = new GroupEntityImpl();
            group.setId(job.getId().toString());
            group.setName(job.getName());
            groups.add(group);
        }
        return groups;
    }

    @Override
    public long findGroupCountByQueryCriteria(GroupQueryImpl query) {
        JobQueryCriteria criteria = new JobQueryCriteria();
        if (ObjectUtils.isNotEmpty(query.getId())) {
            criteria.setId(Long.parseLong(query.getId()));
        }
        criteria.setName(query.getName());
        return jobService.queryAll(criteria).size();
    }

}
